#include <cdefBF537.h>
#include "config.h"
#include "uart.h"

#define SSYNC    asm("ssync;")

void init_uart0(void)
{
    *pPORTF_FER |= 0x0003;  // enable UART0 pins

    *pUART0_GCTL = UCEN;
    *pUART0_LCR = DLAB;
    *pUART0_DLL = UART0_DIVIDER;
    *pUART0_DLH = UART0_DIVIDER >> 8;
    *pUART0_LCR = WLS(8); // 8 bit, no parity, one stop bit

    // dummy reads to clear possible pending errors / irqs
    char dummy = *pUART0_RBR;
    dummy = *pUART0_LSR;
    dummy = *pUART0_IIR;
    SSYNC;
}

void init_uart1(void)
{
    *pPORTF_FER |= 0x000C;  // enable UART1 pins
    *pUART1_GCTL = UCEN;
    *pUART1_LCR = DLAB;
    *pUART1_DLL = UART1_DIVIDER;
    *pUART1_DLH = UART1_DIVIDER >> 8;
    *pUART1_LCR = WLS(8); // 8 bit, no parity, one stop bit

    char dummy = *pUART1_RBR;
    dummy = *pUART1_LSR;
    dummy = *pUART1_IIR;
    SSYNC;
}

void uart0SendChar(unsigned char c)
{
    while (*pPORTHIO & 0x0001)  // hardware serial flow control - 
        continue;               //    S32 pin 17 should be grounded to disable
    while (!(*pUART0_LSR & THRE))
        continue;
    *pUART0_THR = c;
}

void uart0SendString(unsigned char *s)
{
    char a;
    while ((a = *s++)) {
        uart0SendChar(a);
    }
}

void uart0SendChars(unsigned char *buf, unsigned int size)
{
    while (size--) {
        uart0SendChar(*buf++);
    }
}

unsigned char uart0GetCh()
{
    while (!(*pUART0_LSR & DR));
    return *pUART0_RBR;
}

unsigned char uart0GetChar(unsigned char *a)
{
    if (!(*pUART0_LSR & DR))
        return 0;
    *a = *pUART0_RBR;
    return 1;
}
